package com.jd.fruit.common.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.jd.fruit.common.util.WebContextUtil;
import com.jd.fruit.model.admin.auth.AdminUser;
import com.jfinal.handler.Handler;

/**
 * 全局Handler，设置一些通用功能
 * 
 * @author lishunfeng
 */
public class GlobalHandler extends Handler {

	private static Logger log = Logger.getLogger(GlobalHandler.class);

	@Override
	public void handle(String target, HttpServletRequest request,
			HttpServletResponse response, boolean[] isHandled) {
		log.info("设置 web 路径");
		String ctx = WebContextUtil.getContextPath(request);
		String host = WebContextUtil.getEditorHost(request);
		String uri = request.getRequestURI();
		if (uri.contains("/admin/") && !uri.contains("/admin/login")
				&& !uri.contains("/admin/checkLogin")
				&& !uri.contains("/admin/noAuthority")&& !uri.contains("/buyer")) {
			AdminUser user = (AdminUser) request.getSession().getAttribute("loginUser");
			try {
				// session为空从新登陆
				if (user == null) {
					response.sendRedirect(ctx + "/admin/login");
				} 
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// 获取IP归属地
		Object sessonIp = request.getSession().getAttribute("IP");
		if (sessonIp == null) {
			String ip = WebContextUtil.getClientIpAddr(request);
			request.getSession().setAttribute("IP", ip);
		}
		request.setAttribute("ctx", ctx);
		request.setAttribute("host", host);
		nextHandler.handle(target, request, response, isHandled);
	}

}
